<template>
  <div class="container">
    <div
      :class="`tag ${ deletingIdx === i ? 'deleting' : '' }`"
      v-for="(tag, i) in tags"
      :key="i"
    >
      {{ tag }}
      <span @click="onDelete(i)">x</span>
    </div>
    <div v-if="!isAdding" @click="onAdd" class="tag add">+ New Tag</div>
    <input v-focus v-heihei class="tag add" v-else v-model.trim="addValue" type="text" @keyup.enter="onAddOk" @blur="onAddOk">
  </div>
</template>

<script>
export default {
  data () {
    return {
      isAdding: false,
      addValue: '',
      deletingIdx: -1,
      tags: ['aaa', 'bbb', 'cc'],
    };
  },
  methods: {
    onDelete (i) {
      this.deletingIdx = i;
      setTimeout(() => {
        // 500ms后删除数据
        this.tags.splice(i, 1);
        // 置回
        this.deletingIdx = -1;
      }, 500);
    },
    onAdd () {
      this.isAdding = true;
    },
    // 确认添加
    onAddOk () {
      // 置回正在添加的状态
      this.isAdding = false;
      if (!this.addValue) {
        return;
      }
      // 添加数据到数组中
      this.tags.push(this.addValue);
      this.addValue = '';
      // 设置旋转初始状态
      this.deletingIdx = this.tags.length - 1;
      setTimeout(() => {
        this.deletingIdx = -1;
      }, 500);
    },
  },
  // 自定义指令
  directives: {
    focus: {
      // 指令的定义
      inserted (el) {
        // el.focus();
        el.style.border = '3px solid red';
      },
    },
    heihei: {
      // 指令的定义
      inserted (el) {
        // el.focus();
        el.style.background = 'red';
      },
    },
  },
}
</script>

<style scoped>
.tag {
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid skyblue;
  color: skyblue;
  background-color: #ecf5ff;
  display: inline-block;
  margin-left: 8px;
  transition: transform .5s ease;
  transform: rotateY(0deg);
}
.tag.deleting {
  transform: rotateY(90deg);
}
.tag.add {
  border: 1px solid #000;
  color: #000;
  background-color: #fff;
}
</style>